<script setup lang="ts">
import { computed, unref } from 'vue'
import { ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { useLocaleStore } from '@/store/modules/locale'
import { useLocale } from '@/hooks/web/useLocale'
import { propTypes } from '@/utils/propTypes'
import { useDesign } from '@/hooks/web/useDesign'
import { useCache } from '@/hooks/web/useCache'
import { editUserLang } from '@/api/staff'
import { getCurUser } from '@/utils'
const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('locale-dropdown')

defineProps({
  color: propTypes.string.def('')
})

const localeStore = useLocaleStore()

const langMap = computed(() => localeStore.getLocaleMap)

//当前语言
const currentLang = computed(() => localeStore.getCurrentLocale)
let curLang = unref(currentLang).lang

const { wsCache } = useCache()

const setLang = (lang: LocaleType) => {
  if (lang === unref(currentLang).lang) return
  // 需要重新加载页面让整个语言多初始化

  localeStore.setCurrentLocale({
    lang
  })
  const { changeLocale } = useLocale()
  changeLocale(lang)
  //修改缓存的路由
  const groupRouters = wsCache.get('groupRouters') || []
  curLang = lang
  setLang2(curLang)
  switchRouterLang(groupRouters)
  wsCache.set('groupRouters', groupRouters)
}
const setLang2 = async (lang) => {
  let userData = getCurUser()

  if (userData?.userId) {
    await editUserLang({ language: lang, userId: userData.userId }).then((res) => {
      if (res) {
        window.location.reload()
      }
    })
  } else {
    window.location.reload()
  }
}
/**
 * @description: 当切换语言的时候重置路由的title
 * @param routers 路由
 * @author Elwin ZHANG
 * @date 2022/6/1 10:32
 */
const switchRouterLang = (routers: AppCustomRouteRecordRaw[]) => {
  //循环处理
  for (const router of routers) {
    switchOne(router)
  }
}
/***
 * @description: 递归处理每一枝菜单
 * @author Elwin ZHANG
 * @date 2022/6/1 11:27
 */
const switchOne = (router: AppCustomRouteRecordRaw) => {
  if (curLang == 'en') {
    router.meta.title = router.meta.enName
  } else if (curLang == 'zh_HK') {
    router.meta.title = router.meta.hkName
  } else {
    router.meta.title = router.meta.name
  }
  if (!router.children) {
    return
  }
  for (const child of router.children) {
    switchOne(child)
  }
}
</script>

<template>
  <ElDropdown :class="prefixCls" trigger="click" @command="setLang">
    <div style="background: white; border-radius: 2px">
      <Icon
        :size="18"
        icon="ion:language-sharp"
        class="cursor-pointer"
        :class="$attrs.class"
        :color="color"
      />
    </div>
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem v-for="item in langMap" :key="item.lang" :command="item.lang">
          {{ item.name }}
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>
</template>
